#!/usr/bin/python

import sys
import string
import alignment_parse

#Usage: alignment_parse.py <pfam_parse.py output directory> <list of files from pfam_parse.py> <pfam.seed file> <out directory>
if __name__ == "__main__":
	
	#Read the input parameters
	nuc_dir = sys.argv[1]
	list_file = sys.argv[2]
	pfam_seed = sys.argv[3]
	out_dir = sys.argv[4]

	#Open the pfam seed file
	pfamIn = open(pfam_seed, "r")
	
	fam_count = 0

	labels = list()
	seq = list()

	#Get all labels and corresponding aligned sequnces from pfam	
	print("Parsing the pfam.seed file for alignments\n")
	
	while 1:
		line = pfamIn.readline()

		#If the last line, exit the loop
		if not line:
			break

		#If it doesn't start with "#" it is what we want
		line = line.rstrip() 
		if not (line.startswith("#") or line.startswith("//")):
			tokens = line.split()
			tokens[0] = tokens[0].rstrip()			
			labels.append(tokens[0])
			seq.append(tokens[1])
	pfamIn.close()

	print("Total labels found " + str(len(labels)) + "\n")
	sys.stdout.flush()

	#Read all fasta files in pfam-parse output directory
	print("Parsing the list of pfam .fasta files\n")

	file_list = open(list_file,"r")
	all_files = list()

	while 1:
		line = file_list.readline()
		
		if not line:
			break

		line = line.rstrip()
		all_files.append(line)
	
	file_list.close()

	print("Read in " + str(len(all_files)) + " .fasta file names\n")
	sys.stdout.flush()

	#Compute alignment for each fasta file
	print("Reading through each pfam.fasta file to compute alignment\n")

	for a in all_files:
		infile = open(nuc_dir + a , "r")
		outfile = open(out_dir + a +".align","w")
	
		id = ""
		n_seq = ""
		#Read through entire fasta file
		while 1:
			line = infile.readline()
			
			if not line:
				break
			line = line.rstrip()			
			if line.startswith(">"):
				id = line.replace(">","")
			else:
				n_seq = line

			
			#Search for labels in alignment and print alignment to output
			if id != "" and n_seq !="":
				for i in range(len(labels)):
					if id == labels[i]:
						outfile.write(">" + labels[i] + "\n")
						align = alignment_parse.compute_alignment(seq[i], n_seq)
						outfile.write(align + "\n")
						del(labels[i])
						del(seq[i])
						id = ""
						n_seq = ""
						break;		
		outfile.close()
		infile.close()	
		print("Alignment complete for " + a + "\n")
		sys.stdout.flush()

def compute_alignment(p_seq, n_seq):
	align = ""
	
	align_count = 0
	for i in range(len(p_seq)):
		if p_seq[i] == ".":
			align += "..."
		else:
			align += n_seq[align_count*3:align_count*3+3]
			align_count = align_count + 1

	return align
 
def pfam_convert(infile, seq, label):
	print "Parsing the nuc file " + infile
	
	#Open the file for parsing
	input = open(infile, "r")

	while 1:
		line = input.readline()

		#If the last line exit the loop
		if not line:
			break
		
		line.rstrip()

		#Check if it is label in fasta
		if line.startswith(">"):
			string.replace(line,">","")
			label.append(line)

		#If not label then it is seq
		else:
			seq.append(line)				

	#Close the nuc file
	input.close()
